<template>
  <Dialog v-model="dialogVisible" :title="dialogTitle" width="600px">
    <div v-loading="formLoading">
      <el-alert
        :title="alertTitle"
        :type="alertType"
        :closable="false"
        show-icon
      >
        <template #default>
          <p>{{ alertMessage }}</p>
          <p v-if="actionData.candidateCount">影响对象数量：{{ actionData.candidateCount }} 人</p>
        </template>
      </el-alert>
      
      <el-form
        ref="formRef"
        :model="formData"
        :rules="formRules"
        label-width="120px"
        style="margin-top: 20px;"
      >
        <el-form-item label="操作对象" v-if="actionData.candidates && actionData.candidates.length > 0">
          <el-table :data="actionData.candidates" max-height="200" border>
            <el-table-column prop="candidateName" label="姓名" width="100" />
            <el-table-column prop="idCard" label="身份证号" width="180" />
            <el-table-column prop="professionName" label="申报职业" />
            <el-table-column prop="currentStatus" label="当前状态" width="100">
              <template #default="{ row }">
                <el-tag :type="getStatusType(row.currentStatus)">
                  {{ row.currentStatus }}
                </el-tag>
              </template>
            </el-table-column>
          </el-table>
        </el-form-item>
        
        <el-form-item label="操作原因" prop="reason" v-if="requireReason">
          <el-input
            v-model="formData.reason"
            type="textarea"
            :rows="3"
            :placeholder="reasonPlaceholder"
          />
        </el-form-item>
        
        <el-form-item label="处理意见" prop="comments" v-if="requireComments">
          <el-input
            v-model="formData.comments"
            type="textarea"
            :rows="4"
            placeholder="请输入处理意见"
          />
        </el-form-item>
        
        <el-form-item label="通知方式" v-if="actionData.actionType === 'notify'">
          <el-checkbox-group v-model="formData.notificationMethods">
            <el-checkbox label="SMS">短信通知</el-checkbox>
            <el-checkbox label="EMAIL">邮件通知</el-checkbox>
            <el-checkbox label="SYSTEM">系统消息</el-checkbox>
          </el-checkbox-group>
        </el-form-item>
        
        <el-form-item label="执行时间" v-if="actionData.actionType === 'schedule'">
          <el-date-picker
            v-model="formData.executeTime"
            type="datetime"
            placeholder="请选择执行时间"
            style="width: 100%"
          />
        </el-form-item>
        
        <el-form-item label="确认密码" prop="password" v-if="requirePassword">
          <el-input
            v-model="formData.password"
            type="password"
            placeholder="请输入确认密码"
            show-password
          />
        </el-form-item>
        
        <el-form-item>
          <el-checkbox v-model="formData.confirmed">
            我已确认上述操作的影响，并承担相应责任
          </el-checkbox>
        </el-form-item>
      </el-form>
      
      <div class="risk-warning" v-if="isHighRiskAction">
        <el-alert
          title="高风险操作警告"
          type="error"
          :closable="false"
          show-icon
        >
          <template #default>
            <p>此操作属于高风险操作，执行后可能无法撤销，请谨慎操作！</p>
            <p>建议在执行前备份相关数据。</p>
          </template>
        </el-alert>
      </div>
    </div>
    
    <template #footer>
      <el-button 
        @click="confirmAction" 
        :type="buttonType" 
        :disabled="!canConfirm"
        :loading="formLoading"
      >
        {{ confirmButtonText }}
      </el-button>
      <el-button @click="dialogVisible = false">取 消</el-button>
    </template>
  </Dialog>
</template>

<script setup lang="ts">
import { ref, reactive, computed } from 'vue'
import { ElMessage } from 'element-plus'

defineOptions({ name: 'ActionConfirm' })

const emit = defineEmits(['confirm', 'cancel'])

const dialogVisible = ref(false)
const formLoading = ref(false)
const formRef = ref()

const actionData = reactive({
  actionType: '',
  actionName: '',
  candidates: [],
  candidateCount: 0,
  description: ''
})

const formData = reactive({
  reason: '',
  comments: '',
  notificationMethods: [],
  executeTime: null,
  password: '',
  confirmed: false
})

const formRules = computed(() => {
  const rules: any = {}
  
  if (requireReason.value) {
    rules.reason = [{ required: true, message: '请输入操作原因', trigger: 'blur' }]
  }
  
  if (requireComments.value) {
    rules.comments = [{ required: true, message: '请输入处理意见', trigger: 'blur' }]
  }
  
  if (requirePassword.value) {
    rules.password = [{ required: true, message: '请输入确认密码', trigger: 'blur' }]
  }
  
  return rules
})

const dialogTitle = computed(() => {
  const titleMap = {
    approve: '确认审核通过',
    reject: '确认审核拒绝',
    delete: '确认删除',
    batch_approve: '确认批量审核',
    batch_reject: '确认批量拒绝',
    notify: '确认发送通知',
    schedule: '确认定时执行'
  }
  return titleMap[actionData.actionType] || '确认操作'
})

const alertTitle = computed(() => {
  return `即将执行：${actionData.actionName}`
})

const alertType = computed(() => {
  const typeMap = {
    approve: 'success',
    reject: 'warning',
    delete: 'error',
    batch_approve: 'success',
    batch_reject: 'warning',
    notify: 'info',
    schedule: 'info'
  }
  return typeMap[actionData.actionType] || 'info'
})

const alertMessage = computed(() => {
  return actionData.description || '请确认是否执行此操作'
})

const requireReason = computed(() => {
  return ['reject', 'delete', 'batch_reject'].includes(actionData.actionType)
})

const requireComments = computed(() => {
  return ['approve', 'reject', 'batch_approve', 'batch_reject'].includes(actionData.actionType)
})

const requirePassword = computed(() => {
  return ['delete', 'batch_reject'].includes(actionData.actionType)
})

const isHighRiskAction = computed(() => {
  return ['delete', 'batch_reject'].includes(actionData.actionType)
})

const buttonType = computed(() => {
  const typeMap = {
    approve: 'success',
    reject: 'warning',
    delete: 'danger',
    batch_approve: 'success',
    batch_reject: 'warning',
    notify: 'primary',
    schedule: 'primary'
  }
  return typeMap[actionData.actionType] || 'primary'
})

const confirmButtonText = computed(() => {
  const textMap = {
    approve: '确认通过',
    reject: '确认拒绝',
    delete: '确认删除',
    batch_approve: '批量通过',
    batch_reject: '批量拒绝',
    notify: '发送通知',
    schedule: '定时执行'
  }
  return textMap[actionData.actionType] || '确认'
})

const reasonPlaceholder = computed(() => {
  const placeholderMap = {
    reject: '请输入拒绝原因',
    delete: '请输入删除原因',
    batch_reject: '请输入批量拒绝原因'
  }
  return placeholderMap[actionData.actionType] || '请输入操作原因'
})

const canConfirm = computed(() => {
  if (!formData.confirmed) return false
  
  if (requireReason.value && !formData.reason.trim()) return false
  if (requireComments.value && !formData.comments.trim()) return false
  if (requirePassword.value && !formData.password.trim()) return false
  
  if (actionData.actionType === 'notify' && formData.notificationMethods.length === 0) return false
  if (actionData.actionType === 'schedule' && !formData.executeTime) return false
  
  return true
})

/** 打开弹窗 */
const open = async (action: any) => {
  dialogVisible.value = true
  Object.assign(actionData, action)
  resetForm()
}

/** 重置表单 */
const resetForm = () => {
  formData.reason = ''
  formData.comments = ''
  formData.notificationMethods = []
  formData.executeTime = null
  formData.password = ''
  formData.confirmed = false
  formRef.value?.resetFields()
}

/** 获取状态类型 */
const getStatusType = (status: string) => {
  const statusMap = {
    '待审核': 'warning',
    '审核中': 'primary',
    '已通过': 'success',
    '已拒绝': 'danger'
  }
  return statusMap[status] || 'info'
}

/** 确认操作 */
const confirmAction = async () => {
  if (!formRef.value) return
  
  const valid = await formRef.value.validate()
  if (!valid) return
  
  try {
    formLoading.value = true
    
    const confirmData = {
      actionType: actionData.actionType,
      candidates: actionData.candidates,
      reason: formData.reason,
      comments: formData.comments,
      notificationMethods: formData.notificationMethods,
      executeTime: formData.executeTime,
      password: formData.password
    }
    
    emit('confirm', confirmData)
    dialogVisible.value = false
  } catch (error) {
    console.error('确认操作失败:', error)
    ElMessage.error('操作确认失败')
  } finally {
    formLoading.value = false
  }
}

defineExpose({ open })
</script>

<style scoped>
.risk-warning {
  margin-top: 20px;
}

.el-form-item {
  margin-bottom: 20px;
}
</style>
